package com.ruicar.afs.cloud.apply.channel.mq.receiver.processor;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.common.dto.ComAttachmentFileDto;
import com.ruicar.afs.cloud.common.mq.rabbit.listener.AfsMqBizProcessor;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author panhj
 */
@AllArgsConstructor
@Slf4j
@Component
public class ChannelFileToApplyProcessor implements AfsMqBizProcessor<ComAttachmentFileDto> {

    private final ComAttachmentFileService comAttachmentFileService;
    @Override
    public boolean processMessage(ComAttachmentFileDto entity) throws Exception {
        this.saveApplyFile(entity);
        return true;
    }

    @Override
    public MqTransCode getCode() {
        return MqTransCode.CHANNEL_CHANNEL_POS_APPLY_SEND_FILE_TO_APPLY;
    }


    @Transactional(rollbackFor = Exception.class)
    public void saveApplyFile(ComAttachmentFileDto comAttachmentFileDto){
        List<ComAttachmentFile> comAttachmentFileList=comAttachmentFileDto.getComAttachmentFiles();
        List<ComAttachmentFile> comAttachmentFiles=comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo,comAttachmentFileList.get(0).getBusiNo()));
        if(comAttachmentFileList.size()>0){
            for(ComAttachmentFile comAttachmentFile:comAttachmentFiles){
                comAttachmentFileService.removeById(comAttachmentFile);
            }
        }
        for(ComAttachmentFile comAttachmentFile:comAttachmentFileList){
            comAttachmentFile.setId(null);
            comAttachmentFileService.save(comAttachmentFile);
        }
    }
}
